/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mujmail;

import com.sun.lwuit.events.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
import java.io.*;
import javax.microedition.io.file.*;
import javax.microedition.io.*;
import lcduilwuit.Form;
import lcduilwuit.Command;
import com.sun.lwuit.Label;
import com.sun.lwuit.Dialog;
import com.sun.lwuit.Image;
import com.sun.lwuit.util.Resources;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.Component;
import java.util.*;
import com.sun.lwuit.TextArea;
import com.sun.lwuit.plaf.Border;
/**
 *
 * @author anup.s
 */
public class SoundRecordForm extends Form implements ActionListener {

    private SendMail sndMail;
    private Form prevScreen;
    Player recorder;
    RecordControl recordControl;
    Command recordSnd = new Command("Record");
    //Command pauseRecordSnd = new Command("Pause");
    Command stopRecordSnd = new Command("Stop");
    //Command resumeRecordSnd = new Command("Resume");
    Command cancelSnd = new Command("Cancel");
    Label duration = new Label("00:00");
    //byte[] soundBytes;
    private final String SOUND_LOCATION = MujMail.mujmail.getAppProperty("SOUND-LOCATION");
    Timer stopTimer=new Timer();

      int max_length=60;

     FileWriter fWriter=new FileWriter();
    public SoundRecordForm(Form scr, SendMail sndmail) {
        super("Record sound");
        sndMail = sndmail;
        setScrollable(false);
        prevScreen = scr;
        addCommand(cancelSnd);
        addCommand(recordSnd);
        try{
              max_length=Integer.parseInt(MujMail.mujmail.getAppProperty("MAX-VOICEMAIL-LENGTH-IN-MINUTE"));
            }
            catch(Exception e){

            }
         final TextArea textArea = new com.sun.lwuit.TextArea("You can record voice upto " + max_length + " minutes", 5, 5, com.sun.lwuit.TextArea.UNEDITABLE) {

            public int getRows() {
                if (isGrowByContent()) {
                    return getLines();
                } else {
                    return super.getRows();
                }
            }
        };
        textArea.getStyle().setBgTransparency(0);
        textArea.getStyle().setBorder(Border.createEmpty());
        addComponent(textArea);
        setCommandListener(this);

    }


    private void startRecording() {

        try {
            recorder = Manager.createPlayer("capture://audio?encoding=audio/amr");
            recorder.realize();

            recordControl = (RecordControl) recorder.getControl("RecordControl");
            recordControl.setRecordStream(fWriter.getOutputStream());
            recordControl.startRecord();
            recorder.start();
            
            stopTimer.cancel();
            stopTimer=new Timer();
            stopTimer.schedule(new TimerTask() {
                public void run() {
                    actionPerformed(new ActionEvent(stopRecordSnd));
                }
            }, max_length * 60* 1000);
        } catch (Exception e) {
            showError(e.toString());
        }

    }

    private void stopRecording() throws IOException, MediaException {
        recordControl.stopRecord();
        recordControl.commit();
        //bStream.close();
        recorder.stop();
        recorder.close();

    }

    private void discardRecording() throws MediaException,IOException {
        recorder.close();
        fWriter.discard();
    }
    /*
    private void pauseRecording() throws MediaException {

    //player.stop();
    recordControl.stopRecord();
    }

    private void resumeRecording() throws MediaException {
    //player.start();
    recordControl.startRecord();
    }
     */

    public void actionPerformed(ActionEvent ae) {
        com.sun.lwuit.Command cmd = ae.getCommand();
        if (cmd == cancelSnd) {
            prevScreen.show();
        } else if (cmd == recordSnd) {
            startRecording();
            Form frm =new Form("Recording...");
                    frm.addCommand(stopRecordSnd);
                    frm.setCommandListener(this);
                    frm.setLayout(new BorderLayout());
                    Image mic = null;
                    try {
                        mic = Resources.open("/load.res").getImage("mic");

                    } catch (IOException ioe) {
                        //ignore
                    }
                    Label mike = new Label(mic);
                    mike.setAlignment(Component.CENTER);
                    frm.addComponent(BorderLayout.CENTER, mike);
                    frm.show();
//            addCommand(pauseRecordSnd);
            //addCommand(stopRecordSnd);

            /* } else if (cmd == pauseRecordSnd) {
            removeAllCommands();
            addCommand(resumeRecordSnd);
            addCommand(stopRecordSnd);
            try {
            pauseRecording();
            } catch (Exception e) {
            showError(e.toString());
            }*/
        } else if (cmd == stopRecordSnd) {
            stopTimer.cancel();
            try {
                stopRecording();
                //addComponent(new Label("Length is:" + soundBytes.length));
                new SoundPlayerForm().show();
            } catch (Exception e) {
                showError(e.toString());
            }
         //   removeAllCommands();


            /*} else if (cmd == resumeRecordSnd) {
            try {
            resumeRecording();
            } catch (Exception e) {
            showError(e.toString());
            }*/
        }
    }

    private void showError(String err) {
        Dialog.show("ERROR", err, "OK", "");
    }

    private String writeToFile(byte[] data) {
        int trial = 0;
        FileConnection fc = null;
        OutputStream os = null;
        String url = "";
        while (true) {
            try {
                fc = (FileConnection) Connector.open(SOUND_LOCATION + "SonimMail_Recorded_" + (trial++) + ".amr");
                if (!fc.exists()) {
                    url = fc.getURL();
                    fc.create();
                    System.out.println("URL=" + url);
                    break;
                } else {
                    fc.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        try {
            os = fc.openOutputStream();

            os.write(data);

            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (Exception ignored) {
            }
            try {
                fc.close();
            } catch (Exception ignored) {
            }
        }
        return url;
    }
    class FileWriter{

        private OutputStream os;
        private FileConnection fc;
        private String url = "";
        InputStream is;
        OutputStream getOutputStream() throws IOException{
            int trial=0;
           
            while (true) {
           // try {
                fc = (FileConnection) Connector.open(SOUND_LOCATION + "SonimMail_Recorded_" + (trial++) + ".amr");
                if (!fc.exists()) {
                    url = fc.getURL();
                    fc.create();
                    System.out.println("URL=" + url);
                    break;
                } else {
                    fc.close();
             //   }
          //  } catch (Exception e) {
          //      e.printStackTrace();
            }

        }
        
            os = fc.openOutputStream();
            return os;
        
    }
        InputStream getInputStream() throws IOException{
            is= fc.openInputStream();
            return is;
        }
        public String getFileName() {

            try {
                close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return url;
        }
        public long getSize() {
            
                       try{
            return fc.fileSize();
                       }catch(Exception e){
                           return 0;
                       }

        }
        public void discard() throws IOException {

            os.close();
            fc.delete();
            fc.close();
        }

        private void close() throws IOException {

            os.close();
            if(is!=null)
                is.close();
            fc.close();

        }
    }
    class SoundPlayerForm extends Form implements PlayerListener, ActionListener {

        Player player;
        Command playSnd = new Command("Play");
        Command discardSnd = new Command("Discard");
        Command attachSnd = new Command("Attach");
        Command stopPlayingSnd = new Command("Stop");

        SoundPlayerForm() {
            super("Preview");
            addCommand(attachSnd);
            addCommand(playSnd);
            addCommand(discardSnd);
//            String lblTxt="Size: "+(soundBytes.length<1024?""+soundBytes.length+" bytes":""+(soundBytes.length/1000)+"KB");

            setLayout(new BorderLayout());
                    Image fileIcon = null;
                    try {
                        fileIcon = Resources.open("/load.res").getImage("fileicon");

                    } catch (IOException ioe) {
                        //ignore
                    }
                    Label icon = new Label(fileIcon);
         //           icon.setText(lblTxt);
                    icon.setAlignment(Component.CENTER);
                    addComponent(BorderLayout.CENTER, icon);
          //  addComponent(new Label("Size: "+soundBytes.length) );
            setCommandListener(this);
        }

        public void actionPerformed(ActionEvent evt) {
            com.sun.lwuit.Command cmd = evt.getCommand();
            if (cmd == playSnd) {
                try {
                    playRecorded();
                    Form frm =new Form("Playing..");
                    frm.setLayout(new BorderLayout());
                    Image speaker = null;
                    try {
                        speaker = Resources.open("/load.res").getImage("speaker");

                    } catch (IOException ioe) {
                        //ignore
                    }
                    Label spkr = new Label(speaker);
                    spkr.setAlignment(Component.CENTER);
                    frm.addComponent(BorderLayout.CENTER, spkr);
                    frm.addCommand(stopPlayingSnd);
                    frm.setCommandListener(this);
                    frm.show();
                } catch (Throwable t) {
                    showError("T;" + t.toString());
                }
            } else if (cmd == stopPlayingSnd) {
                try {
                    stopPlaying();
                } catch (Exception e) {
                    showError(e.toString());
                }
               show();
            } else if (cmd == discardSnd) {
                try {
                    discardRecording();
                } catch (Exception e) {
                    showError(e.toString());
                }

                SoundRecordForm.this.show();
            } else if (cmd == attachSnd) {
               /* String filePath = writeToFile(soundBytes);
                int size = soundBytes.length;*/
                
                String filePath=fWriter.getFileName();
                int size = (int)fWriter.getSize();
                try{
                    fWriter.close();
                }catch(Exception e){
                    e.printStackTrace();

                }
                BodyPart bp = new BodyPart(new MessageHeader(sndMail.mujMail.outBox), filePath,
                        filePath.substring(filePath.lastIndexOf('/') + 1), filePath.substring(filePath.lastIndexOf('/') + 1), size);

                //   BodyPart bp = new BodyPart(new MessageHeader(mujMail.outBox), "captured_image_"+(captureCount++)+".jpg",rawImage);

                if (sndMail.getAttachementsAdder().getTotalAttachmentSize() + size > Settings.MAX_ATTACHMENT_SIZE_FOR_SENDING) {
                    lcduilwuit.Alert alrt = new lcduilwuit.Alert("ERROR!!!");
                    alrt.setString(Lang.get(Lang.EXTRA_TOTAL_ATTCHMENT_SIZE) + " > " + (Settings.MAX_ATTACHMENT_SIZE_FOR_SENDING / 1000) + "KB");
                    MujMail.mujmail.getDisplay().setCurrent(alrt);
                    return;
                } else {
                    sndMail.getAttachementsAdder().addAttachment(bp);

                    // find file size
                    //((FSStorage) bp.getStorage()).updateSizeInNewThread(new UpdateAttachmentSizeCallback(sendMail, bp));
                }



                if (prevScreen instanceof LwuitUI.Menu) {
                    sndMail.subject.setString("Voicemail");
                    sndMail.writeMail(prevScreen);
                } else {
                    prevScreen.show();
                }
            }
        }

        private void playRecorded() {
            new Thread() {

                public void run() {
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                    try {

                        player = Manager.createPlayer(fWriter.getInputStream()/*new ByteArrayInputStream(soundBytes)*/, "audio/amr");
                        player.realize();
                        player.setMediaTime(0);
                        player.start();
                        player.addPlayerListener(SoundPlayerForm.this);
                    } catch (Exception e) {
                        showError(e.toString() + "I=");
                    }
                }
            }.start();
        }

        private void stopPlaying() throws MediaException {
            player.stop();
            player.close();
        }

        public void playerUpdate(Player plr, String event, Object eventData) {
            if (player == plr && event.equals(PlayerListener.END_OF_MEDIA)) {
                actionPerformed(new ActionEvent(stopPlayingSnd));
            }
        }
    }
}
